<script lang="ts" setup>
import { ref, h, reactive, onMounted, onBeforeMount } from "vue";
import { ReVxeGrid } from "@/components/ReVxeTable";
import { VxeGridPropTypes, VxeUI } from "vxe-table";
import { VxeFormProps, VxeButton, VxeSwitch, VxeImage } from "vxe-pc-ui";
import { ElMessage,UploadUserFile,UploadProps } from "element-plus";
import { upload } from "@/utils/uploadCos";
import addModal from "./components/addModal.vue";
import { dtlList,warnRemove,taxSourcesList,earlyWarnRiskType,listMerchantName,proofUpload } from '@/api/warning/warning'
const reVxeGridRef = ref();
onMounted(() => {
  gettax();
  getrisk();
  getmerchant();
});
// 商户列表
const merchantList = ref<any[]>();
const getmerchant = () => {
  listMerchantName().then((res: any) => {
    merchantList.value = res?.data?.rows;
  });
}
const merchantChanage = () => {
  formOptions.data.taxSourcesId = '';
  gettax();
}
// 税源地列表
const taxList = ref<any[]>();
const gettax = () => {
  taxSourcesList({merchantsInfoId: formOptions.data.merchantsInfoId}).then((res: any) => {
    taxList.value = res?.data?.rows;
  });
};
// 风险类型列表
const riskList = ref<any[]>();
const getrisk = () => {
  earlyWarnRiskType().then((res: any) => {
    riskList.value = res?.data;
  });
}
// 处理方式列表
const stateOptions = ref<any[]>([{
  label: '待审核',
  value: -1
}, {
  label: '待发放',
  value: 1
}, {
  label: '发放成功',
  value: 2
}, {
  label: '发放失败',
  value: 3
}, {
  label: '发放中',
  value: 4
}, {
  label: '已完成',
  value: 6
}, {
  label: '已驳回',
  value: 8
},])
// 验收单状态
const proofOptions = ref<any[]>([{
  label: '未上传验收单',
  value: 0
}, {
  label: '已上传验收单',
  value: 1
}])



const columns: VxeGridPropTypes.Columns<any> = [
  // { type: "checkbox", title: "", width: 60, align: "center" },
  {
    title: "交易订单号",
    field: "tradeOrderNumber",
    align: "center",
    minWidth: 170,
    showOverflow: true
  },
  {
    title: "交易批次号",
    field: "batchNumber",
    align: "center",
    minWidth: 150
  },
  {
    title: "商户名称",
    field: "merchantsInfoIdDisplay",
    align: "center",
    minWidth: 100
  },
  {
    title: "税源地名称",
    field: "taxSourcesIdDisplay",
    align: "center",
    minWidth: 100
  },
  {
    title: "灵工姓名",
    field: "name",
    align: "center",
    minWidth: 80
  },
  {
    title: "下发金额（元）",
    field: "amountOfPayment",
    align: "center",
    minWidth: 80
  },
  {
    title: "发放状态",
    field: "stateDisplay",
    align: "center",
    minWidth: 100
  },
  {
    title: "风险类型",
    field: "riskTypeDisplay",
    align: "center",
    minWidth: 100
  },
  {
    title: "触发规则",
    field: "triggerRuleDisplay",
    align: "center",
    minWidth: 100
  },
  {
    title: "处理频率",
    field: "proofStateDisplay",
    align: "center",
    minWidth: 100
  },
  {
    title: "处理方式",
    field: "stateDisplay",
    align: "center",
    minWidth: 100
  },
  {
    title: "风险原因",
    field: "riskReasons",
    align: "center",
    minWidth: 100
  },
  {
    title: "发放时间",
    field: "timeOfRelease",
    align: "center",
    minWidth: 100
  },
  {
    title: "创建时间",
    field: "lspdewCreateTime",
    align: "center",
    minWidth: 150
  },
  {
    title: "操作",
    field: "operate",
    align: "center",
    fixed: `right`,
    minWidth: 100,
    slots: {
      default: ({ row }) => [
        h(VxeButton, {
          status: "primary",
          mode: "text",
          size: "mini",
          content: "上传验收单",
          onClick() {
            openTwo();
          }
        })
      ]
    }
  }
];
// 筛选相关
const formRef = ref();
interface FormDataVO {
  taxSourcesId: string | number; //税源地
  riskType: string | number; //风险类型
  proofState: string | number; //验收单状态
  tradeOrderNumber: string;//交易订单号
  batchNumber: string;//交易批次号
  name: string;// 灵工姓名
  merchantsInfoId: string | number;
  state: string | number; // 状态
  createTimeStart: number | string; //开始日期
  createTimeEnd: number | string; //结束日期
  timeRang: string[]; //日期数组
}
const formOptions = reactive<VxeFormProps<FormDataVO>>({
  data: {
    taxSourcesId: "",
    riskType: '',
    proofState: '',
    timeRang: [],
    createTimeStart: '',
    createTimeEnd: '',
    tradeOrderNumber: '',
    batchNumber: '',
    name: '',
    merchantsInfoId: '',
    state: '',
  },
  items: [
    {
      field: "tradeOrderNumber",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "tradeOrderNumber" }
    },
    {
      field: "batchNumber",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "batchNumber" }
    },
    {
      field: "name",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "name" }
    },
    {
      field: "merchantsInfoId",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "merchantsInfoId" }
    },
    {
      field: "taxSourcesId",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "taxSourcesId" }
    },
    {
      field: "state",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "state" }
    },
    {
      field: "riskType",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "riskType" }
    },
    {
      field: "proofState",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "proofState" }
    },
    {
      field: "timeRang",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "timeRang" }
    },
    { align: "left", span: 4, slots: { default: "active" } }
  ]
});
// 重置内容
const handleInitialFormParams = () => {
  formOptions.data = <FormDataVO>{
    taxSourcesId: "",
    riskType: '',
    proofState: '',
    timeRang: [],
    createTimeStart: '',
    createTimeEnd: '',
    tradeOrderNumber: '',
    batchNumber: '',
    name: '',
    merchantsInfoId: '',
    state: '',
  };
};
const handleSearch = () => {
  if (formOptions.data?.timeRang?.length) {
    formOptions.data.createTimeStart = formOptions.data.timeRang[0];
    formOptions.data.createTimeStart = formOptions.data.timeRang[1];
  } else {
    formOptions.data.createTimeStart = "";
    formOptions.data.createTimeStart = "";
  }
  reVxeGridRef.value.loadData();
};
const handleReset = async () => {
  await handleInitialFormParams();
  reVxeGridRef.value.loadData("reset");
};

const addModalRef = ref();
const handleAdd = () => {
  addModalRef.value.showAddModal();
};
const handleEdit = (record: Recordable) => {
  addModalRef.value.showEditModal(record);
}
const handleDelete = async (record: Recordable) => {
  const type = await VxeUI.modal.confirm("您确定要删除吗？");
  if (type == "confirm") {
    warnRemove(record.id).then(() => {
      handleSearch();
    });
  }
};

const handleView = (record: Recordable) => {};
const functions: Record<string, string> = {
  add: "platform.client.index.add",
  edit: "platform.client.index.edit",
  view: "platform.client.index.view",
  delete: "platform.client.index.delete"
};



// 上传
const formReftwo = ref();
interface FormDataVOtwo {
  proofUrl: string;
}
const formOptionsTwo = reactive<VxeFormProps<FormDataVOtwo>>({
  data: {
    proofUrl: ""
  },
  items: [
    {
      field: "proofUrl",
      title: "",
      span: 24,
      itemRender: {},
      slots: { default: "proofUrl" }
    }
  ]
});

// 批量上传验收单
const fileList = ref<UploadUserFile[]>([]);
const dialogTwo = ref<boolean>(false);
const openTwo = () => {
  dialogTwo.value = true;
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = rawFile => {
  if (rawFile.size / 1024 / 1024 > 30) {
    ElMessage.error("文件不能大于 30MB!");
    return false;
  }
  return true;
};
const toupload = (params: any) => {
  upload(params.file, res => {
    let index = res.lastIndexOf("/");
    let filename = res.substring(index + 1, res.length);
    let obj = {
      url: `https://${res}`,
      name: filename
    };
    fileList.value.push(obj);
    fileList.value.forEach((item, index) => {
      if (item.status == "ready") {
        fileList.value.splice(index, 1);
      }
    });
  });
};
const submitTwo = () => {
  if (fileList.value.length) {
    let url = [];
    fileList.value.forEach(item => {
      url.push(item.url);
    });
    formOptionsTwo.data.proofUrl = url.join(",");
    proofUpload(formOptionsTwo.data).then(res => {
      dialogTwo.value = false
    })
  }
};
</script>
<template>
  <div>
    <el-card :shadow="`never`" class="table-card">
      <vxe-form ref="formRef" v-bind="formOptions">
        <template #tradeOrderNumber="{ data }">
          <el-input v-model="data.tradeOrderNumber" placeholder="请输入交易订单号"></el-input>
        </template>
        <template #batchNumber="{ data }">
          <el-input v-model="data.batchNumber" placeholder="请输入交易批次号"></el-input>
        </template>
        <template #name="{ data }">
          <el-input v-model="data.name" placeholder="请输入灵工姓名"></el-input>
        </template>
        <template #merchantsInfoId="{ data }">
          <el-select
            clearable
            filterable
            placeholder="请选择商户"
            v-model="data.merchantsInfoId"
            @change="merchantChanage"
          >
            <el-option
              v-for="(item, index) in merchantList"
              :key="index"
              :label="item.merchantsName"
              :value="item.id"
            ></el-option>
          </el-select>
        </template>
        <template #taxSourcesId="{ data }">
          <el-select
            clearable
            placeholder="请选择税源地"
            v-model="data.taxSourcesId"
          >
            <el-option
              v-for="(item, index) in taxList"
              :key="index"
              :label="item.taxSourcesName"
              :value="item.id"
            ></el-option>
          </el-select>
        </template>
        <template #state="{ data }">
          <el-select
            clearable
            placeholder="请选择状态"
            v-model="data.state"
          >
            <el-option
              v-for="(item, index) in stateOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
        <template #riskType="{ data }">
          <el-select
            clearable
            placeholder="请选择风险类型"
            v-model="data.riskType"
          >
            <el-option
              v-for="(item, index) in riskList"
              :key="index"
              :label="item.desc"
              :value="item.code"
            ></el-option>
          </el-select>
        </template>
        <template #proofState="{ data }">
          <el-select
            clearable
            placeholder="请选择验收单状态"
            v-model="data.proofState"
          >
            <el-option
              v-for="(item, index) in proofOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
        <template #timeRang="{ data }">
          <el-date-picker
            clearable
            style="width: 100%"
            v-model="data.timeRang"
            type="daterange"
            range-separator="-"
            value-format="YYYY-MM-DD"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </template>
        <template #active>
          <el-button @click="handleReset" native-type="reset">重置</el-button>
          <el-button @click="handleSearch" native-type="submit" type="primary"
            >提交</el-button
          >
        </template>
      </vxe-form>
    </el-card>
    <el-card :shadow="`never`" class="table-card">
      <ReVxeGrid
        ref="reVxeGridRef"
        :request="dtlList"
        :functions="functions"
        :searchParams="formOptions.data"
        :columns="columns"
        :action="false"
        @handleAdd="handleAdd"
        @handleView="handleView"
        @handleDelete="handleDelete"
      />
    </el-card>
    <addModal ref="addModalRef" @reload="handleSearch" />

    
    <!-- 验收单 -->
    <el-dialog
      v-model="dialogTwo"
      destroy-on-close
      title="上传验收单"
      width="800"
    >
      <div>
        <vxe-form
          ref="formReftwo"
          :title-width="120"
          :title-align="`right`"
          v-bind="formOptionsTwo"
        >
          <template #proofUrl="{ data }">
            <el-upload
              v-model:file-list="fileList"
              class="upload-demo"
              action=""
              accept=".png,.jpg,.jpeg,.pdf,.zip,.rar"
              :limit="20"
              :before-upload="beforeAvatarUpload"
              :http-request="toupload"
            >
              <el-button type="primary">上传验收单</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  请上传 大小不超过 30MB 格式为 jpg/png/jpeg/pdf/zip/rar 的文件
                </div>
              </template>
            </el-upload>
          </template>
        </vxe-form>
        <!-- :on-exceed="handleExceed" -->
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogTwo = false">取消</el-button>
          <el-button type="primary" @click="submitTwo"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style>
.form_header {
  font-size: 15px;
  color: #6379bb;
  border-bottom: 1px solid #ddd;
  padding-bottom: 5px;
}
.left-title {
  font-weight: 700;
  font-family: 微软雅黑;
  font-size: 14px;
  width: 85px;
  text-align: right;
}
.right-text {
  font-size: 14px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #eee;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: #eee;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 138px;
  height: 138px;
  text-align: center;
}
.avatar {
  width: 138px;
  height: 138px;
}
.e_footer {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  background: #fff;
}
.line {
  width: 1px;
  height: 100px;
  border: 1px solid #ededed;
}
</style>
